var map;
var groups = {};      //车辆分组对象
var mks = [];         //存放车辆信息空数组
var userBase = "";    //存放当前登录用户基地权限
$(function () {
    $.ajax({          //获取当前用户的基地权限
        type: "post",
        async: false,
        url: "../map/getBaseByUser",
        success: function (data) {
            if (data == "" || data == null) {  //如果当前用户没有基地权限时，构造塘沽基地用于默认定位到塘沽区域
                userBase = [{"remark": "40.1013888,121.151666", "zoom": 6, "id": "ecd525542ff811e899a100163e032443"}];
            } else {
                userBase = data;          //将基地权限数据赋给全局变量userBase
                userBase[0].zoom = 14;    //自定义一个地图初始的方法级别
                /*加载搜索框内归属地下拉框数据*/
                var txt = '<option value="" selected="true">全部</option>';
                for (var i = 0; i < data.length; i++) {
                    txt += '<option  value="' + data[i].id + '">' + data[i].name + '</option>';
                }
                $('#baseTurn').html(txt);
                $('#baseTurn').selectpicker('refresh');

            }
        }
    })
    var BaseInfo = userBase[0].remark;      //截取存放在备注字段内的字符串
    var newArray = BaseInfo.split(',');     //以逗号分隔经纬度参数

    /**
     * 天地图内容
     */
    /*var normalm = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', {
            maxZoom: 16,
            minZoom: 5
        }),
        normala = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', {
            maxZoom: 16,
            minZoom: 5
        }),
        imgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', {
            maxZoom: 16,
            minZoom: 5
        }),
        imga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', {
            maxZoom: 16,
            minZoom: 5
        });

    var normal = L.layerGroup([normalm, normala]),
        image = L.layerGroup([imgm, imga]);*/
    /**
     * 谷歌
     */
    /*var normalMap = L.tileLayer.chinaProvider('Google.Normal.Map', {
            maxZoom: 16,
            minZoom: 5
        }),
        satelliteMap = L.tileLayer.chinaProvider('Google.Satellite.Map', {
            maxZoom: 16,
            minZoom: 5
        });*/
    /**
     * 高德地图
     */
    /*var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
        maxZoom: 16,
        minZoom: 5
    });
    var Gaodimgem = L.tileLayer.chinaProvider('GaoDe.Satellite.Map', {
        maxZoom: 16,
        minZoom: 5
    });
    var Gaodimga = L.tileLayer.chinaProvider('GaoDe.Satellite.Annotion', {
        maxZoom: 16,
        minZoom: 5
    });
    var Gaodimage = L.layerGroup([Gaodimgem, Gaodimga]);



    var baseLayers = {
        "天地图": normal,
        "天地图影像": image,
        "谷歌地图": normalMap,
        "谷歌影像": satelliteMap,
        "高德地图": Gaode,
        "高德影像": Gaodimage
    }

    map = L.map("mapContent", {
        center: [newArray[0], newArray[1]],
        zoom: userBase[0].zoom,
        layers: [satelliteMap],
        zoomControl: false,
        doubleClickZoom: false,  //禁止双击鼠标放大
        measureControl: true,    //测量工具
    });

    L.control.layers(baseLayers, null).addTo(map);*/


    //初始化地图
    map = L.map('mapContent', {
        center: [newArray[0], newArray[1]], //地图中心点经纬度
        zoom: userBase[0].zoom,             //地图放大级别变量
        maxZoom: 16,                        //最大放大级别
        zoomControl: false,
        doubleClickZoom: false,             //禁止双击鼠标放大
        crs: L.CRS.EPSG4326,
        measureControl: true                //测量工具
    });
    /*底图数据请求地址*/
    var tmsUrl = "http://10.78.178.89:8086/geoserver/gwc/service/tms/1.0.0/leaflet%3Aleaflet_new_wuliu@EPSG%3A4326@png";
    /*右下角自定义信息*/
    var Attrib = '<div id=\'tdiv\' style="padding-right:10px;"></div> &copy <a>资产定位管理系统</a>&nbsp&nbsp&nbsp';

    /*添加底图*/
    var baseLayers = {
        影像底图: L.tileLayer(tmsUrl + '/{z}/{x}/{y}.jpg', {
            minZoom: 6,
            maxZoom: 20,
            attribution: Attrib,
            tms: true
        }).addTo(map)
    }

    //比例尺
    L.control.scale().addTo(map);

    //返回全图
    var zoomHome = L.Control.zoomHome({
        position: 'topright'
    });
    zoomHome.addTo(map);

    //鼠标经纬度
    var conbox = getConboxLatlng();
    //事件监听
    map.on("mousemove", function (e) {
        conbox.update(e) //e为mousemove此事件对象
    })
});

//添加鼠标经纬度
function getConboxLatlng(props) {
    var conBox = L.control({position: 'bottomright'}); //创建右下角控件
    conBox.onAdd = function (map) {  //onAdd方法
        this._div = L.DomUtil.create('div', ''); // create a 'div'
        this.update();
        return this._div;
    };
    // method that we will use to update the control based on feature properties passed
    conBox.update = function (props) {
        if (props)
            this._div.innerHTML = '<div style="padding:10px;opacity:0.8;background:#BAC2D8;border-radius:5px;color:#12385F;font-size:12px;font-weight:bolder;">(' + deg_to_dms(props.latlng.lat) + ',' + deg_to_dms(props.latlng.lng) + ')</div>';
    };
    conBox.addTo(map);
    return conBox
}

//经纬度转换度分秒
function deg_to_dms(deg) {
    var d = Math.floor(deg);
    var minfloat = (deg - d) * 60;
    var m = Math.floor(minfloat);
    var secfloat = (minfloat - m) * 60;
    var s = Math.round(secfloat);
    if (s == 60) {
        m++;
        s = 0;
    }
    if (m == 60) {
        d++;
        m = 0;
    }
    return ("" + d + "°" + m + "'" + s + "\"");
}

/*设置底图容器自适应高度*/
autodivheight();

function autodivheight() { //自适应
    var winHeight = 0;     //获取浏览器窗口高度
    if (window.innerHeight)
        winHeight = window.innerHeight;
    else if ((document.body) && (document.body.clientHeight))
        winHeight = document.body.clientHeight;
    //通过深入Document内部对body进行检测，获取浏览器窗口高度
    if (document.documentElement && document.documentElement.clientHeight)
        winHeight = document.documentElement.clientHeight;
    //自适应为浏览器窗口的高度
    document.getElementById("mapContent").style.height = winHeight - 10 + "px";
}

window.onresize = autodivheight; //浏览器窗口发生变化时同时变化DIV高度

/*判断浏览器版本*/
var browser = navigator.appName;
var b_version = navigator.appVersion;
var version = b_version.split(";");
var trim_Version = version[1].replace(/[ ]/g, "");
if (browser == "Microsoft Internet Explorer" && (trim_Version == "MSIE6.0" || trim_Version == "MSIE7.0" || trim_Version == "MSIE8.0")) {
    alert("浏览器版本过低");
}

$(document).ready(function () {
    vector.loadVector();          //调用画点线面方法
    var baseLayers = {};
    groups = {                    //工具类型分组
        carInfo: new L.LayerGroup().addTo(map)
    };
    var overlays = {              //图层控制
        "车辆": groups.carInfo
    };
    /*图层控制，在底图上添加图层组*/
    L.control.layers(baseLayers, overlays, {}).addTo(map);
    turnType();                   //调用加载搜索框内select下拉框数据
    getToolsData();              //调用接口接加载工具数据
});


/*划分区域*/
var vector = {};
(function (res) {
    res.loadVector = function () {
        $.ajax({
            url: "../map/getVectorGraph",
            dataType: "json",
            success: function (data) {
                res.constructorGeoJson(data);  //画面
            }
        });
    };
    res.constructorGeoJson = function (data) {
        var polygonArray = new Array();//新数组
        var roundArray = new Array();
        for (var i in data) {
            if (data[i].graphType == "3") {
                polygonArray.push(res.constructorPolygon(data[i]));//将面数据添加到polygonArray数组中
            }
            ;
            if (data[i].graphType == "4") {
                roundArray.push(res.constructorRound(data[i]));
            }
        }
        L.geoJSON(polygonArray, {
            style: function (feature) {
                var style = {};
                style.color = feature.properties.color;
                style.fillColor = feature.properties.fillColor;
                style.fillOpacity = 1;
                return style;
            }/*,
            onEachFeature:function(feature, layer){//添加事件和弹出框
                layer.feature = feature;
                layer.on("click",res.cliceTest);
            }*/
        }).addTo(map);
        //创建面的geojson绘画
        res.canvasGeoJson(polygonArray, 3);
        res.canvasGeoJson(roundArray, 4);
    };
    //leaflet原生的geojson绘画方法 type:3面，4圆
    res.canvasGeoJson = function (array, type) {
        if (type == 3) {
            L.geoJSON(array, {
                style: function (feature) {
                    var style = {};
                    style.color = feature.properties.color;
                    style.fillColor = feature.properties.fillColor;
                    style.fillOpacity = 1;
                    return style;
                }/*,
                onEachFeature:function(feature, layer){
                    layer.feature = feature;
                    //绑定面的点击事件
                    if(feature.properties.modelType!=undefined&&feature.properties.modelType!=""){
                        layer.on("dblclick",function(){
                            //点击面的事件
                            //判断点击的是什么模型，根据模型
                            if(feature.properties.modelType=="kf"){
                                $("#kf_dialog").find("#modelId").val(feature.properties.id);
                                $("#kf_dialog").dialog("open");
                            }
                            if(feature.properties.modelType=="lc"){
                                $("#lc_dialog").find("#modelId").val(feature.properties.id);
                                $("#lc_dialog").dialog("open");
                            }
                            if(feature.properties.modelType=="bgcs"){
                                $("#bgcs_dialog").find("#modelId").val(feature.properties.id);
                                $("#bgcs_dialog").dialog("open");
                            }
                            if(feature.properties.modelType=="mt"){
                                $("#mt_dialog").find("#modelId").val(feature.properties.id);
                                $("#mt_dialog").dialog("open");
                            }
                        });
                    }
                    if(feature.properties.showName==0){
                        var popup = L.popup().setLatLng(feature.properties.latlng).setContent("<span>"+feature.properties.name+"</span>");
                        layer.on("mouseover",function(e){
                            //移上的事件
                            map.openPopup(popup);
                        });
                        layer.on("mouseout",function(e){
                            //移出的事件
                            map.closePopup(popup);
                        });
                    }
                }*/
            }).addTo(map);
        } else {
            L.geoJSON(array, {
                pointToLayer: function (feature, latlng) {
                    return L.circle(latlng, {
                        radius: feature.properties.radius,
                        color: feature.properties.color,
                        fill: true, fillColor: feature.properties.fillColor,
                        fillOpacity: 1
                    });
                }/*,
                onEachFeature:function(feature, layer){
                    //绑定面的点击事件
                    if(feature.properties.modelType!=undefined&&feature.properties.modelType!=""){
                        layer.on("click",function(){
                            //点击面的事件
                        });
                    }
                }*/
            }).addTo(map);
        }
    };
    //构造圆的GeoJson数据
    res.constructorRound = function (data) {
        //设置基本属性
        var properties = {};
        properties.id = data.id;
        properties.graphType = data.graphType;
        properties.name = data.name;
        properties.radius = data.radius;
        properties.yradius = data.radius;
        properties.color = data.color;
        properties.fillColor = data.fillColor;
        properties.weight = data.width;
        properties.isHt = false;
        properties.latlng = [data.reservedLat, data.reservedLog];
        properties.showName = data.showName;
        properties.modelType = data.modelType;

        var polyline = {};
        //构造线的坐标数据
        var geometry = {};
        var coordinates = [parseFloat(data.reservedLog), parseFloat(data.reservedLat)];
        geometry.coordinates = coordinates;
        geometry.type = "Point";
        polyline.geometry = geometry;
        polyline.type = "Feature";
        polyline.properties = properties;
        return polyline;
    };
    //构造多边形GeoJson数据
    res.constructorPolygon = function (data) {
        //设置基本属性
        var properties = {};
        properties.id = data.id;
        properties.graphType = data.graphType;
        properties.name = data.name;
        properties.radius = data.radius;
        properties.yradius = data.radius;
        properties.color = data.color;
        properties.fillColor = data.fillColor;
        properties.weight = data.width;
        properties.latlng = [data.reservedLat, data.reservedLog];
        properties.modelType = data.modelType;
        properties.showName = data.showName;
        properties.isHt = false;
        var geoJsonData = {};
        geoJsonData.type = "Feature";
        geoJsonData.properties = properties;

        //创建图形所用的经纬度数组数据
        var coordinates = new Array();
        var polygs = new Array();
        for (var pol in data.vectorGraphPoints) {
            var polyg = [parseFloat(data.vectorGraphPoints[pol].log), parseFloat(data.vectorGraphPoints[pol].lat)];
            polygs.push(polyg);
        }
        coordinates.push(polygs);
        //创建线面坐标信息
        var geometry = {};
        geometry.coordinates = coordinates;
        geometry.type = "Polygon";
        geoJsonData.geometry = geometry;
        return geoJsonData;
    };

    res.constructionData = function (data) {
        //构造geoJsonText的外层结构
        var textArray = new Array();
        var geoJsonText = {};
        geoJsonText.type = "FeatureCollection";
        //构造geoJsonPoint的外层结构
        var pointArray = new Array();
        var geoJsonPoint = {};
        geoJsonPoint.type = "FeatureCollection";
        //构造geoJsonLineString的外层结构
        var lineStringArray = new Array();
        var geoJsonLineString = {};
        geoJsonLineString.type = "FeatureCollection";
        //构造geoJsonMultiPolyg的外层结构
        var multiPolygArray = new Array();
        var geoJsonMultiPolyg = {};
        geoJsonMultiPolyg.type = "FeatureCollection";
        for (var i in data) {
            if (data[i].graphType == "1") {
                //构造文本数据
                textArray.push(res.constrText(data[i]));
            }
            ;
            if (data[i].graphType == "2") {
                lineStringArray.push(res.constrLineString(data[i]));
            }
            ;
            if (data[i].graphType == "3") {
                multiPolygArray.push(res.constrMultiPolyg(data[i]));
            }
            ;
            if (data[i].graphType == "4") {
                pointArray.push(res.constrPoint(data[i]));
            }
            ;
        }
        geoJsonPoint.features = pointArray;
        geoJsonLineString.features = lineStringArray;
        geoJsonMultiPolyg.features = multiPolygArray;
        geoJsonText.features = textArray;
        res.loadPolyg(geoJsonLineString);
        res.loadPolyg(geoJsonMultiPolyg);
        res.loadPolyg(geoJsonPoint);
        res.loadPolyg(geoJsonText);
    };

    //构造文本数据
    res.constrText = function (data) {
        //设置基本属性
        var properties = {};
        properties.id = data.id;
        properties.graphType = data.graphType;
        properties.name = data.name;
        properties.radius = data.radius;
        properties.yradius = data.radius;
        properties.color = data.color;
        properties.fColor = data.fillColor;
        properties.width = data.width;
        properties.isHt = false;

        var polyline = {};
        //构造线的坐标数据
        var geometry = {};
        var coordinates = [parseFloat(data.reservedLog), parseFloat(data.reservedLat)];
        geometry.coordinates = coordinates;
        geometry.type = "Text";
        polyline.geometry = geometry;
        polyline.type = "Feature";
        polyline.properties = properties;
        return polyline;
    };
    //构造点型数据
    res.constrPoint = function (data) {
        //设置基本属性
        var properties = {};
        properties.id = data.id;
        properties.graphType = data.graphType;
        properties.name = data.name;
        properties.radius = data.radius;
        properties.yradius = data.radius;
        properties.color = data.color;
        properties.fColor = data.fillColor;
        properties.width = data.width;
        properties.isHt = false;

        var polyline = {};
        //构造线的坐标数据
        var geometry = {};
        var coordinates = [parseFloat(data.reservedLog), parseFloat(data.reservedLat)];
        geometry.coordinates = coordinates;
        geometry.type = "Point";
        polyline.geometry = geometry;
        polyline.type = "Feature";
        polyline.properties = properties;
        return polyline;

    };
    //构造线型数据
    res.constrLineString = function (data) {

        var polyline = {};
        //设置基本属性
        var properties = {};
        properties.id = data.id;
        properties.graphType = data.graphType;
        properties.name = data.name;
        properties.radius = data.radius;
        properties.color = data.color;
        properties.fColor = data.fillColor;
        properties.width = data.width;

        polyline.type = "Feature";
        //构造线的坐标数据
        var geometry = {};
        var coordinates = new Array();
        for (var pol in data.vectorGraphPoints) {
            var polyg = [parseFloat(data.vectorGraphPoints[pol].log), parseFloat(data.vectorGraphPoints[pol].lat)];
            coordinates.push(polyg);
        }

        geometry.coordinates = coordinates;
        geometry.type = "LineString";
        polyline.geometry = geometry;
        polyline.properties = properties;
        return polyline;
    };
    //构造多边形数据
    res.constrMultiPolyg = function (data) {
        var conData = {};
        conData.type = "Feature";
        //设置基本属性
        var properties = {};
        properties.id = data.id;
        properties.graphType = data.graphType;
        properties.name = data.name;
        properties.radius = data.radius;
        properties.color = data.color;
        properties.fColor = data.fillColor;
        properties.width = data.width;

        conData.properties = properties;

        //创建图形所用的经纬度数组数据
        var coordinates = new Array();
        var polygs = new Array();
        for (var pol in data.vectorGraphPoints) {
            var polyg = [parseFloat(data.vectorGraphPoints[pol].log), parseFloat(data.vectorGraphPoints[pol].lat)];
            polygs.push(polyg);
        }
        coordinates.push(polygs);
        //创建线面坐标信息
        var geometry = {};
        geometry.coordinates = coordinates;
        geometry.type = "Polygon";
        conData.geometry = geometry;
        return conData;
    };
    res.loadPolyg = function (geoJson) {
        var canvasLayer = new L.CanvasGeojsonLayer({
            onMouseOver: function (features) {
                //处理鼠标悬停事件
            },
            onMouseOut: function (features) {
                //处理mouseout事件
            },
            onClick: function (features) {
                //处理鼠标点击事件
            }
        });

        canvasLayer.addTo(map);
        var data = L.CanvasFeatureFactory(geoJson);
        canvasLayer.addCanvasFeatures(data);
        canvasLayer.render();
    };
})(vector);

/**********加载搜索框内归属地、工具类型下拉框数据************/
function turnType() {
    $('#turnType').selectpicker('refresh');//刷新下拉框
    /* 页面加载获取产品下拉框数据 */
    var vehicle_type = 'vehicle_type';
    selecAjax(vehicle_type);
}
/*调用后台接口获取select下拉框数据*/
function selecAjax(item) {
    $.ajax({
        type: "POST",
        data: {
            parentcode: item,
            tool: '123'
        },
        async: true,
        url: '../sysCodeListController/getSysCodeList',
        success: function (res) {
            var res = res.data;
            var txt = '<option value="" selected="true">全部</option>';
            for (var i = 0; i < res.length; i++) {
                if (res[i].parentcode == "vehicle_type") {
                    txt += '<option  value="' + res[i].id + '">' + res[i].name + '</option>';
                    $('#typeTurn').html(txt);
                    $('#typeTurn').selectpicker('refresh');
                }
            }
        }
    });
}
/****************加载下拉框数据结束********************/

/****************搜索按钮点击事件弹出框****************/
function searchToggle(obj, evt) {
    /*closest() 方法获得匹配选择器的第一个祖先元素，从当前元素开始沿 DOM 树向上。*/
    var container = $(obj).closest('.search-wrapper');
    if (!container.hasClass('active')) {
        container.addClass('active');
        $(".searchInfo").css("display", "block");
        $(".search-icon").css("display", "none");
        evt.preventDefault();
    } else if (container.hasClass('active') && $(obj).closest('.input-holder').length == 0) {
        container.removeClass('active');
        $(".searchInfo").css("display", "none");
        $(".search-icon").css("display", "block");
    }
}

/*搜索弹出框内查询按钮点击事件*/
function subSearch() {
    searchToggle($("#boxHide"), event); //搜索按钮点击时，调用隐藏搜索条件方法，关闭搜索框
    groups.carInfo.clearLayers();       //清空图层组里原有的marker数据
    getToolsData();                     //调用加载车辆方法
}
/********************搜索结束***********************/

/********************工具历史轨迹*******************/
var polylineArray = new Array();
var beginBzArray = new Array();

function carsHistoryLocus() {
    cleraCarHistory();          //调用历史轨迹查询时先清除上传的轨迹
    var model = {};
    model.beginTime = $("#beginTime").val();
    model.endTime = $("#endTime").val();
    model.vehicleNo = $("#carId").val();
    $.ajax({
        url: "../map/getVehicleTrajectoryList",
        type: "post",
        data: model,
        success: function (data) {
            if (data.code == 0) {  //存在历史数据
                var hisInfo = data.result;
                if (hisInfo.length > 0) {
                    var latlngs = [];
                    for (var i = 0; i < hisInfo.length; i++) {
                        var beginBz = {};
                        if (i == (hisInfo.length - 1)) {   //终点图标
                            var endIcon = L.icon({
                                iconUrl: '../static/img/zd.png',
                                iconSize: [30, 30],
                                iconAnchor: [15, 30],
                            });
                            beginBz = L.marker([hisInfo[i].latitude, hisInfo[i].longitude], {
                                icon: endIcon,
                                title: new Date(hisInfo[i].collectionTime).Format("yyyy-MM-dd hh:mm:ss")
                            });
                        } else {
                            if (i == 0) {  //起点图标
                                var beginIcon = L.icon({
                                    iconUrl: '../static/img/qd.png',
                                    iconSize: [30, 30],
                                    iconAnchor: [15, 28],
                                });
                                beginBz = L.marker([hisInfo[i].latitude, hisInfo[i].longitude], {
                                    icon: beginIcon,
                                    title: new Date(hisInfo[i].collectionTime).Format("yyyy-MM-dd hh:mm:ss")
                                });
                            } else {  //起点和终点间各点位图标
                                var myIcon = L.icon({
                                    iconUrl: '../static/img/lsjd.png',
                                    iconSize: [12, 12],
                                    iconAnchor: [6, 6],
                                });
                                beginBz = L.marker([hisInfo[i].latitude, hisInfo[i].longitude], {
                                    icon: myIcon,
                                    title: new Date(hisInfo[i].collectionTime).Format("yyyy-MM-dd hh:mm:ss")
                                });
                            }
                        }
                        map.addLayer(beginBz);
                        beginBzArray.push(beginBz);
                        var latlng = new L.LatLng(hisInfo[i].latitude, hisInfo[i].longitude);
                        latlngs.push(latlng);
                    }
                    var polylineOptions = {
                        color: 'blue',
                        weight: 2,
                        dashArray: '5,5',
                        opacity: 0.9
                    };
                    var polyline = new L.Polyline(latlngs, polylineOptions);
                    map.addLayer(polyline);
                    polylineArray.push(polyline);
                    $("#toolInfoDialog").modal("hide");   //关闭弹出框
                }
            } else {   //无历史数据
                layer.msg(data.msg);
            }
        }
    });
}

/*清除历史轨迹*/
function cleraCarHistory() {
    for (var int = 0; int < polylineArray.length; int++) {
        map.removeLayer(polylineArray[int]);
    }
    for (var int = 0; int < beginBzArray.length; int++) {
        map.removeLayer(beginBzArray[int]);
    }
}
/******************历史轨迹结束********************/

//定时器更新工具
var s = setInterval(updateLaz, 60000);

/*****************定时器更新**********************/
function eachLaz(i, item) {
    var marks = groups.carInfo.getLayers();
    for (var i = 0; i < marks.length; i++) {
        var title = marks[i].options.title;
        if (title == item.vehiclName) {
            //setLatLng是设置这个marker的经纬度，直接操作图标的经纬度，不会出现刷新图标的现象了
            if(item.latitude!="" && item.latitude!=null && item.longitude!="" && item.longitude!=null) {
                marks[i].dragging._marker.setLatLng([item.latitude, item.longitude]);
            }
        }
    }
};

//修改marker位置
function updateLaz(e) {
    var base = $("#baseTurn").val() == null ? "" : $("#baseTurn").val();
    var type = $("#typeTurn").val() == null ? "" : $("#typeTurn").val();
    var no = $("#no").val();
    $.get("../map/getVehicle", {base: base, type: type, no: no}, function (data) {
        $.each(data, function (i, items) {
            eachLaz(i, items); //调用drawcb方法，加载marker标记及弹框数据
        });
    });
};
/******************定时器更新车辆任务结束*****************/

/*调用后台接口获取工具数据*/
function getToolsData() {
    var base = $("#baseTurn").val() == null ? "" : $("#baseTurn").val();
    var type = $("#typeTurn").val() == null ? "" : $("#typeTurn").val();
    var no = $("#no").val();
    $.get("../map/getVehicle", {base: base, type: type, no: no}, function (data) {
        if (data == "" || data == null) {
            mks = new Array();                          //将全局变量mks中上次存入的数据清空
            var item = "";
            darTools(item, base, type, no);             //调用drawcar方法，加载mark标记及弹框数据
        } else {
            mks = new Array();                          //将全局变量mks中上次存入的数据清空
            $.each(data, function (index, item) {
                darTools(item, base, type, no);         //调用drawcar方法，加载mark标记及弹框数据
            });
            map.on('zoomend', onMapLevel);             //监听zoomend事件（即地图放大缩小事件），发生此事件时执行onMapLevel函数
        }
    });
}

/*显示工具图标*/
function darTools(item, base, type, no) {
    if(item==""||item==null){
        /*判断搜索条件中归属地不为空时切换基地*/
        if (base != "" || base != null) {
            for (var i = 0; i < userBase.length; i++) {
                if (userBase[i].id == base) {
                    var jwdInfo = userBase[i].remark;   //截取存放在备注字段内的字符串
                    var jwdArray = jwdInfo.split(','); //以逗号分隔经纬度参数
                    map.setView([jwdArray[0], jwdArray[1]], map.getZoom());
                }
            }
        }
    }else{
        var carsIcon = L.icon({iconUrl: '../static/img/car_little.png', iconSize: [20, 20], iconAnchor: [10, 18]});
        if(item.imgRemark==""||item.imgRemark==null){
            thisIcon = L.icon({iconUrl: '../static/img/cl.png', iconSize: [30, 30], iconAnchor: [10, 18]});
        }else{
            thisIcon = L.icon({iconUrl: '../static/img/'+item.imgRemark, iconSize: [30, 30], iconAnchor: [10, 18]});
        }
        var allIcon = [carsIcon, thisIcon];
        var mk = {};

        /*工具marker下方文字标记*/
        var toolsmsg = L.divIcon({
            className: 'my-div-icon',
            html: '<p  class=\'map-label\'>' + item.vehiclName + '</p>' //工具名称
        });

        /*将文字标记添加到groups分组图层中*/
        var txtMark = L.marker([item.latitude, item.longitude], {icon: toolsmsg, title: item.vehiclName});

        /*判断搜索条件中归属地不为空时切换基地*/
        if (base != "" || base != null) {
            for (var i = 0; i < userBase.length; i++) {
                if (userBase[i].id == base) {
                    var jwdInfo = userBase[i].remark;   //截取存放在备注字段内的字符串
                    var jwdArray = jwdInfo.split(','); //以逗号分隔经纬度参数
                    map.setView([jwdArray[0], jwdArray[1]], map.getZoom());
                }
            }
        }

        /*判断搜索条件中编码不为空时定位车辆，并高亮显示*/
        if (no != "" && no != null) {
            if (item.no == no) {
                if(item.latitude!="" && item.latitude!=null && item.longitude!="" && item.longitude!=null) {
                    map.setView([item.latitude, item.longitude], map.getZoom());    //定位
                    mk = L.marker([item.latitude, item.longitude], {               //创建marker图标
                        icon: allIcon[0],
                        title: item.vehiclName
                    }).addTo(groups.carInfo);
                    var id = mk._leaflet_id;  //存当前处于高亮状态下的marker的id
                    mk.enablePermanentHighlight();                                 //设置高亮
                    if (mk.options.highlight == "permanent") {                         //判断当前marker是否有高亮属性，有则10s后清除高亮
                        /*10s过后清除当前高亮*/
                        setTimeout(function () {
                            mk.disablePermanentHighlight();
                        }, 10000);
                    }
                    /*设置开始缩放事件，主要用于清除缩放时出现多个高亮的情况*/
                    map.on("zoomstart", updateMk);

                    function updateMk() {
                        if(id = mk._leaflet_id){
                            mk.disablePermanentHighlight();
                        }
                        /*setTimeout(function () {
                            mk.disablePermanentHighlight();
                        }, 5000);*/
                    }
                }
            }
        } else {
            if(item.latitude!="" && item.latitude!=null && item.longitude!="" && item.longitude!=null){
                if(map.getZoom()<16) {  //当地图当前级别小于16级时，marker图标显示圆点
                    mk = L.marker([item.latitude, item.longitude], {
                        icon: allIcon[0],
                        title: item.vehiclName,
                    }).addTo(groups.carInfo);
                }else{                 //当地图当前级别大于16级时，marker图标显示为具体工具图标
                    mk = L.marker([item.latitude, item.longitude], {
                        icon: allIcon[1],
                        title: item.vehiclName,
                    }).addTo(groups.carInfo);
                    txtMark.addTo(groups.carInfo);
                }
            }
        }

        /*定义空对象，用于存放当前获取的数据穿件的marker信息*/
        var tool = {};
        tool.id = item.id;
        tool.mk = mk;
        tool.txMk = txtMark;
        tool.icons = allIcon;
        tool.no = item.no;
        tool.base = item.base;
        tool.baseName = item.baseName;
        tool.typeName = item.typeName;
        mks.push(tool);   //将车辆id和marker标记添加至car对象中，给定位使用

        /*工具图标点击弹出框*/
        if(item.latitude!="" && item.latitude!=null && item.longitude!="" && item.longitude!=null) {
            mk.on("click", function (e) {
                var titleInfo = item.vehiclName + "【" + item.no + "】";
                basicInfo(titleInfo);  //调用方法
                $("#carId").val(item.no); //隐藏域给历史轨迹用
            })
        }

        /*加载车辆详细信息*/
        function basicInfo(titleInfo) {
            $("#toolInfoDialog").modal("show");
            $("#toolDialogTitle").html(titleInfo);
            var html = "";
            /*时间格式转换*/
            var data = new Date(item.manufactureDate).Format("yyyy-MM-dd");
            html += "<table class='table table-bordered'>" +
                "<tr><td class='titleCol'>车辆类型</td>" + "<td>" + item.typeName + "</td><td class='titleCol'>车辆名称</td>" + "<td>" + item.vehiclName + "</td></tr>" +
                "<tr><td class='titleCol'>车辆编号</td>" + "<td>" + item.no + "</td><td class='titleCol'>规格型号</td>" + "<td>" + item.specificationsName + "</td></tr>" +
                "<tr><td class='titleCol'>车牌号</td>" + "<td>" + item.plateNumber + "</td><td class='titleCol'>状态</td>" + "<td>" + item.statusStr + "</td></tr>" +
                "<tr><td class='titleCol'>归属地</td>" + "<td colspan='3'>" + item.baseName + "</td></tr>" +
                "<tr><td class='titleCol'>当前位置</td>" + "<td colspan='3'>" + "经度：" + item.longitude + "," + "纬度：" + item.latitude + "," + "区域：" + item.areaName + "</td></tr>" +
                "</table>"
            $("#carDetailInfo").html(html);                 //将拼接的html内天添加到DOM元素上
        }
    }

    laydate.skin('molv');
    /* 设置时间插件的皮肤 */
    var start = {
        elem: '#beginTime',                             //选择ID为START的input
        format: 'YYYY-MM-DD hh:mm:ss',                  //自动生成的时间格式
        max: laydate.now(),                             //最大日期
        istime: true,
        istoday: true,                                 //是否显示今天
        start: laydate.now(0, "YYYY-MM-DD hh:mm:ss"),  //设置开始时间为当前时间
        choose: function (datas) {
            over.min = datas;                          //开始日选好后，重置结束日的最小日期
        }
    };
    var over = {
        elem: '#endTime',
        format: 'YYYY-MM-DD hh:mm:ss',
        max: laydate.now(),
        istime: true,
        istoday: true,                                 //是否显示今天
        start: laydate.now(0, "YYYY-MM-DD hh:mm:ss"),
        choose: function (datas) {
            start.max = datas;                         //结束日选好后，重置开始日的最大日期
        }
    };
    laydate(start);
    laydate(over);
    $('#beginTime').val(laydate.now(-1, 'YYYY-MM-DD hh:mm:ss'));
    $('#endTime').val(laydate.now(0, 'YYYY-MM-DD hh:mm:ss'));
}

var ischange = false;       //是否把工具图片改为点
var isadd = true;         //是否显示文字标注
function onMapLevel() {
    if (map._zoom < 16) {  //当地图缩放级别低于15时
        if (isadd == false) {
            for (var i = 0; i < mks.length; i++) {
                groups.carInfo.removeLayer(mks[i].txMk);  //当地图小于15级且不显示文字时移除改marker文字
            }
            isadd = true;
        }
        if (ischange == true) {  //当地图级别为14、13……时，ischange = false，停止重复加载
            for (var i = 0; i < mks.length; i++) {
                mks[i].mk.setIcon(mks[i].icons[0]);       //设置marker为圆点
            }
            ischange = false;
        }
    } else { //当地图缩放级别大于15时
        if (isadd == true) {                              //当地图大于15级且显示文字时将marker添加到图层组中
            for (var i = 0; i < mks.length; i++) {
                mks[i].txMk.addTo(groups.carInfo);
            }
            isadd = false;
        }
        if (ischange == false) {                         //当地图级别为16、17……时，ischange = true，停止重复加载
            for (var i = 0; i < mks.length; i++) {
                mks[i].mk.setIcon(mks[i].icons[1]);
            }
            ischange = true;
        }
    }
}

// 对Date的扩展，将 Date 转化为指定格式的String
Date.prototype.Format = function (fmt) { //author: zhengsh 2016-9-5
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
